<template>
    <div class="detail-container">
        <el-card class="detail-card" shadow="never">
            <!-- 顶部标题和操作区域 -->
            <div class="header-section">
                <div class="title-area">
                    <h2 class="title">
                        {{ info.customerName || '-' }} {{ info.customerCode || '' }}
                    </h2>
                    <el-icon @click="handleCopy" class="copy-icon" title="复制">
                        <DocumentCopy />
                    </el-icon>
                </div>
                <div class="action-area">
                    <div class="status-info">
                        <span class="status-label">状态</span>
                        <el-tag v-if="String(info.customerState) === '0'" type="success" size="large">启用</el-tag>
                        <el-tag v-else-if="String(info.customerState) === '1'" type="danger" size="large">禁用</el-tag>
                        <span v-else>-</span>
                    </div>
                    <div class="action-buttons">
                        <el-button type="primary" @click="handleEdit">编辑</el-button>
                        <el-button type="danger" @click="handleDelete">删除</el-button>
                        <el-button type="warning" @click="handleDisable">停用</el-button>
                        <el-button @click="handlePrint">打印</el-button>
                    </div>
                </div>
            </div>

            <!-- 客户基本信息 -->
            <div class="info-card">
                <el-descriptions :column="4" border>
                    <el-descriptions-item label="客户名称">
                        <span class="info-value">{{ info.customerName || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="客户编码">
                        <span class="info-value">{{ info.customerCode || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="所属行业">
                        <span class="info-value">{{ info.industryName || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="客户来源">
                        <span class="info-value">{{ info.customerSourceName || '-' }}</span>
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions :column="3" border class="info-row">
                    <el-descriptions-item label="联系人">
                        <span class="info-value">{{ info.customerContact || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="联系电话">
                        <span class="info-value">{{ info.contactPhone || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="电子邮箱">
                        <span class="info-value">{{ info.customerEmail || '-' }}</span>
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions :column="3" border class="info-row">
                    <el-descriptions-item label="销售部门">
                        <span class="info-value">{{ info.organizationName || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="销售负责人">
                        <span class="info-value">{{ info.userName || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="客户状态">
                        <el-tag v-if="String(info.customerState) === '0'" type="success">启用</el-tag>
                        <el-tag v-else-if="String(info.customerState) === '1'" type="danger">禁用</el-tag>
                        <span v-else>-</span>
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions :column="1" border class="info-row">
                    <el-descriptions-item label="客户地址">
                        <span class="info-value">{{ info.contactAddress || '-' }}</span>
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions :column="1" border class="info-row">
                    <el-descriptions-item label="备注">
                        <span class="info-value">{{ info.customerNote || '-' }}</span>
                    </el-descriptions-item>
                </el-descriptions>

                <!-- 审核信息 -->
                <el-descriptions :column="4" border class="audit-row">
                    <el-descriptions-item label="创建人">
                        <span class="info-value">{{ info.createor || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="创建时间">
                        <span class="info-value">{{ formatDate(info.createrTime) }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="更新人">
                        <span class="info-value">{{ info.updator || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="更新时间">
                        <span class="info-value">{{ formatDate(info.updateTime) }}</span>
                    </el-descriptions-item>
                </el-descriptions>
            </div>

            <!-- 标签页区域 -->
            <div class="tabs-section">
                <el-tabs v-model="activeTab" type="card" class="detail-tabs">
                    <!-- 其他信息标签页 -->
                    <el-tab-pane label="其他信息" name="other">
                        <div class="tab-content">
                            <!-- 财务信息 -->
                            <div class="section-block">
                                <h3 class="section-title">财务信息</h3>
                                <el-descriptions :column="2" border>
                                    <el-descriptions-item label="账户名称">
                                        <span class="info-value">{{ info.financeName || '-' }}</span>
                                    </el-descriptions-item>
                                    <el-descriptions-item label="纳税人识别号">
                                        <span class="info-value">{{ info.taxpayerNumber || '-' }}</span>
                                    </el-descriptions-item>
                                    <el-descriptions-item label="银行账户">
                                        <span class="info-value">{{ info.bankAccount || '-' }}</span>
                                    </el-descriptions-item>
                                    <el-descriptions-item label="开户银行">
                                        <span class="info-value">{{ info.accountBank || '-' }}</span>
                                    </el-descriptions-item>
                                    <el-descriptions-item label="开户行地址" :span="2">
                                        <span class="info-value">{{ info.bankAddress || '-' }}</span>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>

                            <!-- 附件 -->
                            <div class="section-block">
                                <h3 class="section-title">附件</h3>
                                <div class="attachment-list">
                                    <el-link v-for="(file, index) in attachments" :key="index" :href="file.url"
                                        :underline="false" type="primary" class="file-link" target="_blank">
                                        📎 {{ file.name }}
                                    </el-link>
                                    <div v-if="attachments.length === 0" class="empty-text">暂无附件</div>
                                </div>
                            </div>

                            <!-- 自定义字段 -->
                            <div class="section-block">
                                <h3 class="section-title">自定义字段</h3>
                                <div v-if="customFields.filter(f => f.value).length === 0" class="empty-text">
                                    暂无自定义字段
                                </div>
                                <el-descriptions v-else :column="2" border>
                                    <el-descriptions-item v-for="(field, index) in customFields.filter(f => f.value)"
                                        :key="index" :label="field.label">
                                        <span class="info-value">{{ field.value }}</span>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>
                        </div>
                    </el-tab-pane>

                    <!-- 销售记录标签页 -->
                    <el-tab-pane label="销售记录" name="sale">
                        <div class="tab-content">
                            <el-table v-if="salesRecords.length" :data="salesRecords" border stripe
                                v-loading="salesLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="salesOrderNo" label="销售单号" min-width="160" />
                                <el-table-column label="单据状态" width="110">
                                    <template #default="{ row }">
                                        <el-tag :type="getSalesStatusTag(row.salesOrderStatus)" size="small">
                                            {{ getSalesStatusText(row.salesOrderStatus) }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="salesOrderDate" label="销售日期" width="140">
                                    <template #default="{ row }">
                                        {{ formatDate(row.salesOrderDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="organizationName" label="销售部门" min-width="150" />
                                <el-table-column prop="userName" label="销售负责人" width="120" />
                                <el-table-column prop="salesContact" label="联系人" width="120" />
                                <el-table-column prop="salesContactPhone" label="联系电话" width="140" />
                                <el-table-column prop="salesOrderQuantity" label="销售数量" width="110" align="right" />
                                <el-table-column label="销售金额" width="130" align="right">
                                    <template #default="{ row }">
                                        ¥{{ Number(row.salesOrderAmount ?? 0).toFixed(2) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="salesGoodsText" label="销售货品" min-width="220"
                                    show-overflow-tooltip />
                                <el-table-column prop="salesOrderUser" label="制单人" width="120" />
                            </el-table>
                            <el-empty v-else-if="!salesLoading" description="暂无销售记录" />
                        </div>
                    </el-tab-pane>

                    <!-- 出库记录标签页 -->
                    <el-tab-pane label="出库记录" name="outbound">
                        <div class="tab-content">
                            <el-table v-if="outboundRecords.length" :data="outboundRecords" border stripe
                                v-loading="outboundLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="outboundCode" label="出库单号" min-width="160" />
                                <el-table-column label="单据状态" width="110">
                                    <template #default="{ row }">
                                        <el-tag :type="getOutboundStatusTag(row.outboundCodeState)" size="small">
                                            {{ getOutboundStatusText(row.outboundCodeState) }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="outboundDate" label="出库日期" width="140">
                                    <template #default="{ row }">
                                        {{ formatDate(row.outboundDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="outboundTypeName" label="出库类型" width="140" />
                                <el-table-column prop="warehouseName" label="仓库名称" min-width="150" />
                                <el-table-column prop="outboundQuantity" label="出库数量" width="110" align="right" />
                                <el-table-column label="出库金额" width="130" align="right">
                                    <template #default="{ row }">
                                        ¥{{ Number(row.outboundAmount ?? row.outboundMoney ?? 0).toFixed(2) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="handlerProple" label="经办人" width="120" />
                                <el-table-column prop="documentCreator" label="制单人" width="120" />
                                <el-table-column prop="documentCreation" label="制单时间" width="160">
                                    <template #default="{ row }">
                                        {{ formatDate(row.documentCreation) }}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-empty v-else-if="!outboundLoading" description="暂无出库记录" />
                        </div>
                    </el-tab-pane>

                    <!-- 入库记录标签页 -->
                    <el-tab-pane label="入库记录" name="inbound">
                        <div class="tab-content">
                            <el-table v-if="inboundRecords.length" :data="inboundRecords" border stripe
                                v-loading="inboundLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="warehousingCode" label="入库单号" min-width="160" />
                                <el-table-column prop="warehousingTypeName" label="入库类型" width="140" />
                                <el-table-column prop="storageDate" label="入库日期" width="140">
                                    <template #default="{ row }">
                                        {{ formatDate(row.storageDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="warehouseName" label="仓库" min-width="150" />
                                <el-table-column prop="warehousingNum" label="入库数量" width="110" align="right" />
                                <el-table-column label="入库金额" width="130" align="right">
                                    <template #default="{ row }">
                                        ¥{{ Number(row.warehousingMoney ?? 0).toFixed(2) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="documentCreator" label="制单人" width="120" />
                                <el-table-column prop="reviewerPeople" label="审核人" width="120" />
                            </el-table>
                            <el-empty v-else-if="!inboundLoading" description="暂无入库记录" />
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-card>

        <div class="detail-footer">
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { DocumentCopy } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import myaxios from '@/http/MyAxios'

const route = useRoute()
const router = useRouter()

// 当前激活的标签页
const activeTab = ref('other')

// 客户详情信息
const info = reactive({
    customerId: route.query.customerId || '',
    customerCode: '',
    customerName: '',
    industryId: '',
    industryName: '',
    customerSourceId: '',
    customerSourceName: '',
    customerContact: '',
    contactPhone: '',
    customerEmail: '',
    organizationId: '',
    organizationName: '',
    userId: '',
    userName: '',
    customerState: '',
    contactAddress: '',
    customerNote: '',
    financeId: '',
    financeName: '',
    taxpayerNumber: '',
    bankAccount: '',
    accountBank: '',
    bankAddress: '',
    createor: '',
    createrTime: '',
    updator: '',
    updateTime: '',
})

// 附件列表
const attachments = ref<Array<{ name: string; url: string }>>([])

// 自定义字段（当前无实际数据，占位）
const customFields = ref<Array<{ label: string; value: string }>>([
    { label: '自定义字段1', value: '' },
    { label: '自定义字段2', value: '' },
    { label: '自定义字段3', value: '' },
])

// 关联记录
const salesRecords = ref<any[]>([])
const outboundRecords = ref<any[]>([])
const inboundRecords = ref<any[]>([])
const operationRecords = ref<any[]>([])
const salesLoading = ref(false)
const outboundLoading = ref(false)
const inboundLoading = ref(false)
const operationLoading = ref(false)

// 格式化日期
const formatDate = (date: any) => {
    if (!date) return '-'
    try {
        return moment(date).format('YYYY-MM-DD HH:mm:ss')
    } catch (error) {
        return date
    }
}

const SALES_STATUS_OPTIONS = [
    { value: 0, label: '草稿', tagType: 'info' },
    { value: 1, label: '待审核', tagType: 'warning' },
    { value: 2, label: '驳回', tagType: 'danger' },
    { value: 3, label: '部分出库', tagType: 'warning' },
    { value: 4, label: '已完成', tagType: 'success' },
    { value: 5, label: '已关闭', tagType: 'info' },
]

const OUTBOUND_STATUS_OPTIONS = [
    { value: 0, label: '草稿', tagType: 'info' },
    { value: 1, label: '待审核', tagType: 'warning' },
    { value: 2, label: '已完成', tagType: 'success' },
    { value: 3, label: '已关闭', tagType: 'danger' },
]

const getSalesStatusText = (status: any) => {
    const target = SALES_STATUS_OPTIONS.find(item => Number(item.value) === Number(status))
    return target?.label || '未知'
}

const getSalesStatusTag = (status: any) => {
    const target = SALES_STATUS_OPTIONS.find(item => Number(item.value) === Number(status))
    return target?.tagType || 'info'
}

const getOutboundStatusText = (status: any) => {
    const target = OUTBOUND_STATUS_OPTIONS.find(item => Number(item.value) === Number(status))
    return target?.label || '未知'
}

const getOutboundStatusTag = (status: any) => {
    const target = OUTBOUND_STATUS_OPTIONS.find(item => Number(item.value) === Number(status))
    return target?.tagType || 'info'
}

const matchesCurrentCustomer = (row: any) => {
    if (!row) return false
    const currentId = info.customerId || route.query.customerId
    const recordId = row.customerId || row.CustomerId
    if (currentId && recordId !== undefined && recordId !== null && String(recordId) === String(currentId)) {
        return true
    }
    const currentName = info.customerName || route.query.customerName
    const recordName = row.customerName || row.CustomerName || row.supplierName || row.contactName
    return Boolean(currentName && recordName && String(currentName) === String(recordName))
}

const extractGoodsNames = (row: any): string[] => {
    if (!row) return []
    if (Array.isArray(row.productDisplayList) && row.productDisplayList.length) {
        return row.productDisplayList
    }
    if (Array.isArray(row.goodsDetails) && row.goodsDetails.length) {
        return row.goodsDetails.map((item: any) => item.productName || item.goodsName || '').filter(Boolean)
    }
    if (Array.isArray(row.salesOrderDetails) && row.salesOrderDetails.length) {
        return row.salesOrderDetails.map((item: any) => item.productName || item.goodsName || '').filter(Boolean)
    }
    const candidateString =
        row.productDisplayText ||
        row.productNames ||
        row.productName ||
        row.goodsNames ||
        row.goodsListText ||
        ''
    if (typeof candidateString === 'string' && candidateString.trim()) {
        return candidateString
            .split(/[,，\s]/)
            .map(item => item.trim())
            .filter(Boolean)
    }
    if (Array.isArray(candidateString)) {
        return candidateString.filter(Boolean)
    }
    return []
}

const normalizeList = (payload: any): any[] => {
    if (!payload) return []
    if (Array.isArray(payload)) return payload
    const candidateKeys = ['data', 'records', 'list', 'items']
    for (const key of candidateKeys) {
        if (Array.isArray(payload?.[key])) {
            return payload[key]
        }
    }
    if (Array.isArray(payload?.pages?.data)) {
        return payload.pages.data
    }
    return []
}

const mapSalesRecord = (item: any) => {
    const goodsNames = extractGoodsNames(item)
    return {
        ...item,
        salesOrderQuantity: Number(item.salesOrderQuantity ?? item.quantity ?? 0),
        salesOrderAmount: Number(item.salesOrderAmount ?? item.amount ?? 0),
        salesGoodsText: goodsNames.length ? goodsNames.join('，') : (item.productName || '-'),
    }
}

const fetchSalesRecords = async () => {
    if (!info.customerId && !info.customerName) return
    salesLoading.value = true
    try {
        const res = await myaxios.get('/api/SalesOrder/GetSalesOrders', {
            params: {
                customerId: info.customerId || route.query.customerId,
                customerName: info.customerName || route.query.customerName,
                pageindex: 1,
                pagesize: 20,
            },
        })
        if (res.data?.code === 200) {
            const list = normalizeList(res.data.data)
            const filtered = list.filter(matchesCurrentCustomer)
            salesRecords.value = filtered.map(mapSalesRecord)
        } else {
            salesRecords.value = []
        }
    } catch (error) {
        console.error('获取销售记录失败:', error)
        salesRecords.value = []
    } finally {
        salesLoading.value = false
    }
}

const mapOutboundRecord = (item: any) => ({
    ...item,
    outboundCode: item.outboundCode || item.outboundNo || item.deliveryNo || '',
    outboundCodeState: item.outboundCodeState ?? item.outboundStatus ?? item.state ?? '',
    outboundDate: item.outboundDate || item.deliveryDate || item.createTime || '',
    outboundTypeName: item.outboundTypeName || item.outboundType || '',
    warehouseName: item.warehouseName || item.warehouse || '',
    outboundQuantity: Number(item.outboundQuantity ?? item.outboundNum ?? item.deliveryNum ?? 0),
    outboundAmount: Number(item.outboundAmount ?? item.outboundMoney ?? item.totalAmount ?? 0),
    handlerProple: item.handlerProple || item.handler || '',
    documentCreator: item.documentCreator || item.createor || item.creator || '',
    documentCreation: item.documentCreation || item.createTime || item.createrTime || '',
})

const fetchOutboundRecords = async () => {
    if (!info.customerId && !info.customerName) return
    outboundLoading.value = true
    try {
        const res = await myaxios.get('/api/Outbound/GetOutbound', {
            params: {
                customerId: info.customerId || route.query.customerId,
                customerName: info.customerName || route.query.customerName,
                pageindex: 1,
                pagesize: 20,
            },
        })
        if (res.data?.success || res.data?.code === 200) {
            const dataSection = res.data?.data || {}
            const list = normalizeList(dataSection)
            const filtered = list.filter(matchesCurrentCustomer)
            outboundRecords.value = filtered.map(mapOutboundRecord)
        } else {
            outboundRecords.value = []
        }
    } catch (error) {
        console.error('获取出库记录失败:', error)
        outboundRecords.value = []
    } finally {
        outboundLoading.value = false
    }
}

const mapInboundRecord = (item: any) => ({
    ...item,
    warehousingCode: item.warehousingCode || item.warehousingNo || item.inboundNo || '',
    warehousingTypeName: item.warehousingTypeName || item.warehousingType || item.typeName || '',
    storageDate: item.storageDate || item.warehousingDate || item.inboundDate || item.createTime || '',
    warehouseName: item.warehouseName || item.warehouse || '',
    warehousingNum: Number(item.warehousingNum ?? item.inboundQuantity ?? item.quantity ?? 0),
    warehousingMoney: Number(item.warehousingMoney ?? item.amount ?? item.totalAmount ?? 0),
    documentCreator: item.documentCreator || item.createor || item.creator || '',
    reviewerPeople: item.reviewerPeople || item.auditor || item.reviewer || '',
})

const fetchInboundRecords = async () => {
    if (!info.customerId && !info.customerName) return
    inboundLoading.value = true
    try {
        const res = await myaxios.get('/api/Warehousing/GetWarehousing', {
            params: {
                customerId: info.customerId || route.query.customerId,
                customerName: info.customerName || route.query.customerName,
                pageindex: 1,
                pagesize: 20,
            },
        })
        if (res.data?.success || res.data?.code === 200) {
            const dataSection = res.data?.data || {}
            const list = normalizeList(dataSection)
            const filtered = list.filter(matchesCurrentCustomer)
            inboundRecords.value = filtered.map(mapInboundRecord)
        } else {
            inboundRecords.value = []
        }
    } catch (error) {
        console.error('获取入库记录失败:', error)
        inboundRecords.value = []
    } finally {
        inboundLoading.value = false
    }
}

const resolveOperationType = (type: string) => {
    const map: Record<string, string> = {
        新增: '新增',
        创建: '新增',
        create: '新增',
        Create: '新增',
        修改: '修改',
        更新: '修改',
        编辑: '修改',
        Update: '修改',
        编辑中: '修改',
        删除: '删除',
        Delete: '删除',
        审核: '审核',
        打印: '打印',
        导出: '导出',
    }
    return map[type] || type || '未知'
}

const resolveOperationContent = (item: any, code?: string) => {
    const content =
        item.operationContent ||
        item.operateContent ||
        item.description ||
        item.content ||
        item.actionDescription ||
        ''
    if (content) return content
    if (code) {
        return `${resolveOperationType(item.operationType || item.operateType || item.type || '')}客户【${code}】`
    }
    return '操作记录'
}

const fetchOperationRecords = async () => {
    if (!info.customerId && !info.customerName) return
    operationLoading.value = true
    try {
        const params: any = {
            customerId: info.customerId || route.query.customerId,
            businessId: info.customerId || route.query.customerId,
            moduleCode: 'Customer',
            moduleName: '客户管理',
            businessType: 'Customer',
            pageindex: 1,
            pagesize: 20,
        }
        const apiCandidates = [
            '/api/Customer/GetOperationRecords',
            '/api/OperationLog/GetOperationRecords',
            '/api/Log/GetOperationRecords',
            '/api/Customer/GetCustomerOperationLog',
            '/api/OperationLog/GetList',
        ]
        let success = false
        for (const api of apiCandidates) {
            try {
                const res = await myaxios.get(api, { params })
                if (res.data?.code === 200) {
                    const list = normalizeList(res.data.data)
                    const filtered = list.filter((item: any) => {
                        if (matchesCurrentCustomer(item)) return true
                        const content = item.operationContent || item.description || ''
                        if (content && info.customerName && content.includes(info.customerName)) return true
                        const moduleCode = item.moduleCode || item.module
                        const moduleName = item.moduleName || item.businessModuleName
                        return moduleCode === 'Customer' || moduleName === '客户管理'
                    })
                    operationRecords.value = filtered.map((item: any) => ({
                        ...item,
                        operator: item.operator || item.operateUser || item.userName || item.createUser || '',
                        creator: item.creator || item.createor || info.createor || '',
                        operationType: resolveOperationType(item.operationType || item.operateType || item.type || ''),
                        operationContent: resolveOperationContent(item, info.customerCode || info.customerName),
                        operationTime: item.operationTime || item.operateTime || item.createTime || item.createrTime || '',
                    }))
                    success = true
                    break
                }
            } catch (error) {
                console.warn(`接口 ${api} 加载失败`, error)
            }
        }
        if (!success) {
            operationRecords.value = []
        }
    } catch (error) {
        console.error('获取操作记录失败:', error)
        operationRecords.value = []
    } finally {
        operationLoading.value = false
    }
}

const loadRelatedRecords = () => {
    fetchSalesRecords()
    fetchOutboundRecords()
    fetchInboundRecords()
    fetchOperationRecords()
}

// 加载客户详情
const loadCustomerDetail = () => {
    const customerId = route.query.customerId
    if (!customerId) {
        ElMessage.error('客户ID不能为空')
        router.push('/GetCustomer')
        return
    }

    myaxios.get(`api/Customer/GetCustomerById?customerId=${customerId}`).then((res: any) => {
        if (res.data.code === 200) {
            const data = res.data.data
            Object.assign(info, {
                customerId: data.customerId,
                customerCode: data.customerCode,
                customerName: data.customerName,
                industryId: data.industryId,
                industryName: data.industryName,
                customerSourceId: data.customerSourceId,
                customerSourceName: data.customerSourceName,
                customerContact: data.customerContact,
                contactPhone: data.contactPhone,
                customerEmail: data.customerEmail,
                organizationId: data.organizationId,
                organizationName: data.organizationName,
                userId: data.userId,
                userName: data.userName,
                customerState: data.customerState,
                contactAddress: data.contactAddress,
                customerNote: data.customerNote,
                financeId: data.financeId,
                financeName: data.financeName,
                taxpayerNumber: data.taxpayerNumber,
                bankAccount: data.bankAccount,
                accountBank: data.accountBank,
                bankAddress: data.bankAddress,
                createor: data.createor,
                createrTime: data.createrTime,
                updator: data.updator,
                updateTime: data.updateTime,
            })

            if (data.files && Array.isArray(data.files)) {
                attachments.value = data.files.map((file: any) => ({
                    name: file.fileName,
                    url: file.fileUrl,
                }))
            } else {
                attachments.value = []
            }

            loadRelatedRecords()
        } else {
            ElMessage.error(res.data.message || '获取客户详情失败')
            router.push('/GetCustomer')
        }
    }).catch((err: any) => {
        console.error('获取客户详情失败:', err)
        ElMessage.error('获取客户详情失败')
        router.push('/GetCustomer')
    })
}

// 复制功能
const handleCopy = async () => {
    try {
        const textToCopy = `${info.customerName || ''} ${info.customerCode || ''}`.trim()
        if (!textToCopy) {
            ElMessage.warning('暂无可复制内容')
            return
        }
        await navigator.clipboard.writeText(textToCopy)
        ElMessage.success('复制成功')
    } catch (error) {
        ElMessage.error('复制失败，请手动复制')
        console.error('复制失败:', error)
    }
}

// 编辑
const handleEdit = () => {
    if (!info.customerId) {
        ElMessage.error('客户ID不能为空')
        return
    }
    router.push({
        path: '/UpdateCustomer',
        query: { customerId: String(info.customerId) },
    })
}

// 删除
const handleDelete = () => {
    if (!info.customerId) {
        ElMessage.error('客户ID不能为空')
        return
    }

    ElMessageBox.confirm(
        '确认删除该客户吗？',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        },
    )
        .then(() => {
            myaxios.put(`api/Customer/DeleteCustomer?customerid=${info.customerId}`).then((res: any) => {
                if (res.data.code === 200) {
                    ElMessage.success(res.data.message || '删除成功')
                    router.push('/GetCustomer')
                } else {
                    ElMessage.error(res.data.message || '删除失败')
                }
            }).catch((error: any) => {
                console.error('删除失败:', error)
                ElMessage.error('删除失败')
            })
        })
        .catch(() => {
            ElMessage.info('已取消删除')
        })
}

// 停用
const handleDisable = () => {
    ElMessageBox.confirm(
        '确认停用该客户吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        },
    )
        .then(() => {
            ElMessage.success('停用功能成功')
        })
        .catch(() => {
            ElMessage.info('已取消停用')
        })
}

// 打印
const handlePrint = () => {
    window.print()
}

// 关闭并返回客户列表
const handleClose = () => {
    router.push('/GetCustomer')
}

onMounted(() => {
    loadCustomerDetail()
})
</script>

<style scoped>
.detail-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 60px);
}

.detail-card {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0;
    border-radius: 8px;
    overflow: hidden;
}

.detail-footer {
    max-width: 1400px;
    margin: 16px auto 0;
    text-align: right;
}

/* 顶部标题和操作区域 */
.header-section {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 24px 24px 20px;
    border-bottom: 1px solid #e4e7ed;
    background-color: #fff;
}

.title-area {
    display: flex;
    align-items: center;
    flex: 1;
}

.title {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin: 0;
    margin-right: 12px;
}

.copy-icon {
    cursor: pointer;
    color: #606266;
    font-size: 20px;
    transition: color 0.2s;
}

.copy-icon:hover {
    color: #409eff;
}

.action-area {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 12px;
}

.status-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.status-label {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
}

.action-buttons {
    display: flex;
    gap: 8px;
}

/* 基本信息卡片 */
.info-card {
    padding: 24px;
    background-color: #fff;
}

.info-row {
    margin-top: 16px;
}

.audit-row {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 2px solid #e4e7ed;
}

.info-value {
    color: #303133;
    font-size: 14px;
}

/* 标签页区域 */
.tabs-section {
    padding: 0 24px 24px;
    background-color: #fff;
}

.detail-tabs {
    margin-top: 20px;
}

.tab-content {
    padding: 20px 0;
    min-height: 300px;
}

.section-block {
    margin-bottom: 32px;
}

.section-block:last-child {
    margin-bottom: 0;
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 16px 0;
    padding-bottom: 8px;
    border-bottom: 2px solid #409eff;
}

.attachment-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.file-link {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 8px 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: all 0.2s;
}

.file-link:hover {
    border-color: #409eff;
    background-color: #ecf5ff;
}

.empty-text {
    color: #909399;
    font-size: 14px;
    padding: 20px 0;
    text-align: center;
}

/* Element Plus 样式覆盖 */
:deep(.el-descriptions__label) {
    font-weight: 500;
    background-color: #fafafa;
    width: 120px;
    color: #606266;
}

:deep(.el-descriptions__content) {
    background-color: #fff;
    color: #303133;
}

:deep(.el-tabs__header) {
    margin: 0 0 20px 0;
}

:deep(.el-tabs__item) {
    font-size: 14px;
    padding: 0 20px;
    height: 40px;
    line-height: 40px;
}

:deep(.el-tabs__item.is-active) {
    color: #409eff;
    font-weight: 500;
}

:deep(.el-descriptions__table) {
    border-collapse: separate;
    border-spacing: 0;
}

:deep(.el-descriptions__cell) {
    padding: 12px 16px;
}

/* 打印样式 */
@media print {
    .detail-container {
        background-color: #fff;
        padding: 0;
    }

    .action-area {
        display: none;
    }

    .detail-tabs {
        display: none;
    }

    .tabs-section {
        display: none;
    }
}
</style>
